package com.samphanie.ane.core.security.handler;

import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.util.StandardCharset;
import com.samphanie.ane.common.utils.CommonResult;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;

/**
 * @Author ZSY
 * @createTime 2021/3/13 16:01
 */
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());

        val data = new HashMap<String, Object>();
        data.put(
                "timestamp",
                Calendar.getInstance().getTime()
        );

        data.put(
                "exception",
                e.getLocalizedMessage()
        );

        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        response.getWriter()
                .println(JSONUtil.toJsonStr(CommonResult.unauthorized(data)));

    }

}
